﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Hangout.Web.Services.Location
{
    public class UserLocation
    {
         Hangout.Web.Model.HangoutDBEntities context = new Web.Model.HangoutDBEntities();
        public  void UpdateUserLocation(Services.Objects.Location location, string accessToken)
        {
            try
            {
                if (location != null)
                {
                    if (Web.Core.Accounts.User.IsValid((int)location.UserID, accessToken, context))
                    {
                        Model.Location loc = new Model.Location();
                        loc.UserID = location.UserID;
                        loc.Longitude = location.Longitude;
                        loc.Latitude = location.Latitude;


                        Hangout.Web.Core.Location.UserLocation.UpdateUserLocation(loc, ref context);
                    }
                    else { throw new Web.Core.Exceptions.Account.UnAuthorisedAccess(); }
                }
            }
            catch (System.Exception ex)
            {
                Web.Core.Exceptions.ExceptionReporting.AddAnException(0, Web.Core.ClientType.WindowsAzure, ex, ref context);
            }
        }


        public  List<Web.Core.Location.UserLocationData> GetNearestUsers(int userid, int count, string accesstoken)
        {
            try
            {
                if (Web.Core.Accounts.User.IsValid((int)userid, accesstoken, context))
                {
                    return Hangout.Web.Core.Location.UserLocation.GetNearestUsers(userid, count, ref context);
                }

                else { throw new Web.Core.Exceptions.Account.UnAuthorisedAccess(); }
            }
            catch (System.Exception ex)
            {
                Web.Core.Exceptions.ExceptionReporting.AddAnException(userid, Web.Core.ClientType.WindowsAzure, ex, ref context);
                return null;
            }
        }

        public  Objects.Location GetLocation(int locationId, string accessToken)
        {
            try
            {
                if (Web.Core.Accounts.User.IsValid(accessToken, context))
                {
                    Model.Location location= Hangout.Web.Core.Location.Location.GetLocation(locationId, ref context);
                    return new Objects.Location { Latitude = location.Latitude, Longitude = location.Longitude };
                }

                else { throw new Web.Core.Exceptions.Account.UnAuthorisedAccess(); }
            }
            catch (System.Exception ex)
            {
                Web.Core.Exceptions.ExceptionReporting.AddAnException(0, Web.Core.ClientType.WindowsAzure, ex, ref context);
                return null;
            }
        }
    }
}